package com.exampleyyy.demoyyy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.exampleyyy.demoyyy.JieKouService.AddressBookServiceJieKou;
import com.exampleyyy.demoyyy.JieKouShiTiYYY.AddressBookJieKou;
import com.exampleyyy.demoyyy.ShiTiYYY.AddressBook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookService extends ServiceImpl<AddressBookJieKou, AddressBook> implements AddressBookServiceJieKou {

    @Override
    public List<AddressBook> listByUserId(Long userId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId)
                .orderByDesc(AddressBook::getIsDefault)
                .orderByDesc(AddressBook::getUpdateTime);
        return this.list(queryWrapper);
    }

    @Override
    public AddressBook getDefaultByUserId(Long userId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1);
        return this.getOne(queryWrapper);
    }


    @Override
    @Transactional
    public void setDefaultAddress(Long id, Long userId) {
        // 1. 将当前用户所有地址设为非默认
        LambdaQueryWrapper<AddressBook> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, userId);

        AddressBook nonDefault = new AddressBook();
        nonDefault.setIsDefault(0);
        this.update(nonDefault, updateWrapper);

        // 2. 将指定地址设为默认
        AddressBook defaultAddress = new AddressBook();
        defaultAddress.setId(id);
        defaultAddress.setIsDefault(1);
        this.updateById(defaultAddress);
    }
}